var Kapow = Kapow || {};

Kapow.Lectern = function () {
  var IMAGES_ARRAY_SIZE = 8;
  var images = $A();
  var cursor = 0;
  var archivePath = '';

  // PUBLIC INTERFACE
  this.initialise = function (path, pagenum) {
    archivePath = path;
    var imagesDiv = $('images');
    for (i = 0; i < IMAGES_ARRAY_SIZE; i++) {
      images[i] = document.createElement('img');
      images[i].index = i;
      imagesDiv.appendChild(images[i]);
    }

    load(
      pagenum,
      function () {
        $('functionBar').style.visibility = "visible"; 
        preload(pagenum + 1);
      }
    );
  }

  this.next = function () {
    var pagenum = currPagenum();
    load(pagenum + 1, function () { preload(pagenum + 2); });
  }

  this.previous = function () {
    var pagenum = currPagenum();
    if (pagenum > 0) {
      load(pagenum - 1);
    }
  }

  // METHODS GENERALLY INTENDED FOR INTERNAL USE 
  var load = function (pagenum, lCallback) {
    var onload = function (img) { flip(img, lCallback); }

    for (var i = 0; i < images.length; i++) {
      if (imgPagenum(images[i]) == pagenum) {
        onload(images[i]);
        return;
      }
    }

    preload(pagenum, onload);
  }
 
  var preload = function (pagenum, pCallback) {
    var img = images[(cursor + 1) % IMAGES_ARRAY_SIZE];

    new Ajax.Request(
      '/turn?path='+escape(archivePath)+'&pagenum='+pagenum,
      { 
        method: 'get',
        onSuccess: function (transport) {
          if (typeof pCallback == 'function') {
            img.onload = function () { pCallback(img) }
          } else {
            img.onload = null;
          }
          var atts = eval('(' + transport.responseText + ')');
          for (var att in atts) {
            img.setAttribute(att, atts[att]);
          }
        }
      }
    );
  }

  var flip = function (toImg, fCallback) {
    var oldcursor = cursor;
    images[oldcursor].style.visibility = "hidden";
    setTimeout(
      function () {
        cursor = toImg.index;
        toImg.style.visibility = 'visible';
        toImg.style.display = 'block';
        window.scrollTo(0, 1);

        var unit = (toImg.offsetHeight / 3.0);
        var panels = $$('.panel');
        for (var i = 0; i < panels.length; i++) {
          var panel = panels[i];
          var multiplier = Math.floor(i / 2);
          panel.style.height = unit + "px";
          panel.style.top = unit * multiplier + "px";
        }

        $('pagenum').innerHTML = currPagenum() + 1;

        images[oldcursor].style.display = 'none';
        
        if (typeof fCallback == 'function') { fCallback(toImg); }
      },
      20
    );
  }

  var currPagenum = function () {
    return imgPagenum(images[cursor]);
  }

  var imgPagenum = function (img) {
    return parseInt(img.getAttribute('pagenum'));
  }
}
